package com.yjz.middleware.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;


/**
 * channelHandler
 *
 * @author :yuanJinZhong
 * @description: 什么也不做的协议Discard, 丢弃的意思，服务端丢弃，那就是啥也不做的协议呗
 * @date :2018/10/29-22:51
 */
@Slf4j
@ChannelHandler.Sharable
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    log.info("server received :" + in.toString(CharsetUtil.UTF_8));
//    ByteBuf out=  ByteBufAllocator.DEFAULT.buffer().writeBytes("这是服务端给你发的消息".getBytes(Charset.forName("GBK")));
//    ctx.write(out);
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ByteBuf byteBuf=Unpooled.buffer().writeBytes("这是服务端给你发的消息/n".getBytes(Charset.forName("GBK")));
      ByteBuf out=  ByteBufAllocator.DEFAULT.buffer().writeBytes("这是服务端给你发的消息/n".getBytes(Charset.forName("GBK")));
//    ByteBuf out=  PreferHeapByteBufAllocator.DEFAULT.buffer().writeBytes("这是服务端给你发的消息/n".getBytes(Charset.forName("GBK")));
    log.info("是否有backing array :{}",byteBuf.hasArray());
    ctx.writeAndFlush(byteBuf);
//      .addListener(ChannelFutureListener.CLOSE);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
